<!-- @formatter:off -->
<route lang="json5" type="home">
{
  style: {
    backgroundColor: '#ffffff',
  },
}
</route>
<!-- @formatter:on -->

<script setup lang="ts">
import GradientButton from '@/components/use-btn/index.vue'
import useLogin from '@/hooks/useLogin'
import { OptionsCallback } from '@/models/login'
import { HOME_PAGE, LOGIN_PAGE, Status } from '@/models/sys'
import VerificationCodeView from '@/pages/login/components/verification-code-view.vue'
import { useUserStore } from '@/store/user'
import { isPC } from '@/utils'
import LogoImage from '@/static/images/sys/logo.png'
import _ from 'lodash'

// #ifdef MP-WEIXIN
uni.hideHomeButton()
// #endif

onShareAppMessage(() => {
  return {
    title: import.meta.env.VITE_APP_TITLE,
    path: `${LOGIN_PAGE}?app_id=${getAppId()}`,
  }
})

onLoad(async (options) => {
  const {
    miniProgram: { envVersion },
  } = uni.getAccountInfoSync()

  if (import.meta.env.VITE_APP_ID && envVersion !== 'release') {
    setAppId(import.meta.env.VITE_APP_ID)
  }

  if (options?.secondary === '1') {
    secondary.value = true
    uni.showModal({
      title: '二次验证',
      content: '请二次验证扫码',
      showCancel: false,
      confirmText: '前往验证',
      confirmColor: '#ff4d07',
      success: (res) => {
        if (res.confirm) {
          onLoginClick()
        }
      },
    })
  }
  uni.showLoading({ title: '加载中' })
  isLoading.value = true

  const appId = getAppId() || ''
  if (options?.app_id) {
    setAppId(options.app_id)
    // if (!useUserStore().userInfo.token)
    // await callback.getLogin()
    // if (!isPC()) {
    //   await callback.getLogin()
    // }
  } else {
    // setTimeout(() => {
    //   if (!appId) {
    //     uni.hideLoading()
    //     uni.showModal({
    //       content: '小程序未配置app_id，请联系管理员',
    //       title: '提示',
    //       showCancel: false,
    //       confirmText: '好的',
    //     })
    //   }
    // }, 1000)
  }
  await callback.getLogin()
  uni.hideLoading()
  await callback.checkLoginResult()
  isLoading.value = false

  if (useUserStore().userInfo.token) callback.openTimer()
})

const showQrcode = ref<boolean>(false)
const showVerificationCode = ref<boolean>(false)

function handleClose() {
  // if(checkLoginData.value.need_secondary_qrcode)
  showQrcode.value = false
  showVerificationCode.value = false
  callback.closeTimer()
}

function showVerificationClose() {
  verificationCodeRef.value?.clean()
  showVerificationCode.value = false
  isScanCode.value = false
  callback.closeTimer()
  verifyCode.value = ''
}

const onLoginClick = _.debounce(
  async () => {
    // 判断设备登录类型
    if (!isPC()) {
      uni.showModal({
        title: '提示',
        content: '请使用PC端小程序扫码登录',
        showCancel: false,
        confirmText: '确认',
        confirmColor: '#ff4d07',
      })

      return
    }
    await callback.getIpadLoginQrCode(() => {
      showQrcode.value = true
      isScanCode.value = true
    })
  },
  500,
  {
    leading: true,
    trailing: false,
  },
)

const isNeedQrCode = ref(false)
const isOpen = ref(false)
const { setWxUserStatus, setAppId, getAppId, isLogined } = useUserStore()
const isPadding = ref(false)

/** 是否为扫码步骤 */
const isScanCode = ref(false)
const optionsCallback: OptionsCallback = {
  successLogin() {
    if (isPadding.value) return
    isPadding.value = true
    uni.hideLoading()

    callback.closeTimer()
    setWxUserStatus(Status.Yes)
    if (secondary.value) {
      uni.showToast({
        title: '验证成功',
      })
    } else {
      uni.showToast({
        title: '登录成功',
      })
    }
    setTimeout(() => {
      uni.hideLoading()
      uni.reLaunch({
        url: HOME_PAGE,
      })
    }, 500)
  },
  needQrcode() {
    if (!isPC()) return
    isNeedQrCode.value = true
  },
  scanQrcode() {
    if (!isPC()) return
    showQrcode.value = true
  },
  needCode() {
    if (!isPC()) return
    if (verifyCode.value) return
    if (!isScanCode.value) return
    uni.hideLoading()

    showVerificationCode.value = true
    showQrcode.value = false
  },
  needSecondaryQrcode() {
    if (!isPC()) return
    showQrcode.value = true
  },
}

const { qrcode, checkLoginData, ...callback } = useLogin(optionsCallback)
const isLoading = ref(false)
const secondary = ref(false)

onUnload(() => {
  uni.hideLoading()
  callback.closeTimer()
})

const verificationCodeRef = ref<InstanceType<typeof VerificationCodeView>>()
const verificationCodeLogin = _.debounce(
  () => {
    if (verifyCode.value.length !== 6) {
      uni.showToast({ title: '请输入6位数验证码', icon: 'none' })
      return
    }
    uni.showLoading({ title: '请稍等', mask: true })
    callback.verifyCode(
      { code: verifyCode.value },
      () => {
        uni.showToast({ title: '提交成功' })
        showVerificationCode.value = false

        setTimeout(() => {
          uni.showLoading({ title: '登录中', mask: true })
        }, 500)
      },
      () => {
        // verifyCode.value = ''
      },
    )
  },
  500,
  {
    leading: true,
    trailing: false,
  },
)

const verifyCode = ref('')
function codeInput(val: string) {
  verifyCode.value = val
}

const logo = ref(LogoImage)
</script>

<template>
  <view class="flex-container">
    <view class="flex items-center flex-col pt-35">
      <image :src="logo" class="logo"></image>
      <view class="mt-18 text-center text-title-style">家校沟通AI助手</view>
      <view class="text-content-style mt-6">-开启效率提升之旅-</view>
    </view>
    <GradientButton class="ml-4 mr-4 mt-30" @click="onLoginClick">
      {{ secondary ? '点击二次验证扫码登录' : '点击扫码登录' }}
    </GradientButton>

    <wd-popup
      v-model="showQrcode"
      position="bottom"
      :closable="true"
      custom-style="border-radius:32rpx 32rpx 0 0;"
      @close="handleClose"
    >
      <view class="custom-txt mt-2.5">
        <wd-text text="请扫码登录" color="#2B2F36" size="36rpx"></wd-text>
        <view class="h-2"></view>
        <wd-img :width="210" :height="210" :src="qrcode" />
        <view
          class="text-content-hint-style mt-6 mb-35.5"
          :style="secondary ? 'color:#ff4d07' : ''"
        >
          {{ secondary ? '请使用企业微信二次扫码' : '请使用企业微信扫码登录' }}
        </view>
      </view>
    </wd-popup>

    <wd-popup
      v-model="showVerificationCode"
      position="bottom"
      :closable="true"
      custom-style="border-radius:32rpx 32rpx 0 0;"
      @close="showVerificationClose"
    >
      <view>
        <view class="custom-txt mt-2.5">
          <wd-text text="请输入验证码" color="#2B2F36" size="36rpx"></wd-text>
          <verification-code-view
            class="mt-25"
            v-if="showVerificationCode"
            ref="verificationCodeRef"
            style="align-items: center"
            @input="codeInput"
          ></verification-code-view>
          <view class="text-content-hint-style mt-6 mb-30">请输入设备验证码</view>
          <!-- <view class="text-content-hint-style mt-15 mb-10" style="color: #ff4d07">
            验证失败，请稍后重试
          </view> -->
          <GradientButton :width="670" class="ml-4 mr-4 mb-20" @click="verificationCodeLogin">
            登录
          </GradientButton>
        </view>
      </view>
    </wd-popup>
  </view>
</template>

<style scoped lang="scss">
.text-title-style {
  font-size: 44rpx;
  font-style: normal;
  font-weight: 800;
  line-height: 54rpx;
  color: #2b2f36;
  text-align: center;
}

.text-content-style {
  font-size: 36rpx;
  font-style: normal;
  font-weight: 400;
  color: #9fa3aa;
  text-align: center;
}

.text-content-hint-style {
  font-size: 32rpx;
  font-style: normal;
  font-weight: 400;
  color: #aaaaaa;
  text-align: center;
}
/*
.gradient-button {
  background: linear-gradient(135deg, #fcff5e 0%, #cfff69 49%, #6efffd 100%), #ffdb00;
  border-radius: 60rpx;
  border: none;
  color: #2b2f36;
  font-size: 32rpx;
  height: 92rpx;
  font-weight: 600;
  box-sizing: border-box;
}
*/

.flex-container {
  display: flex;
  flex-direction: column;
  height: 100vh;

  .logo {
    width: 200rpx;
    height: 200rpx;
    border-radius: 32rpx;
  }
}

.custom-txt {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 400rpx;
  color: black;
  border-radius: 32rpx;
}
</style>
